package org.shopen.ai.puremvc.view.project
{
	import mx.collections.ArrayCollection;
	import mx.events.ItemClickEvent;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	import org.shopen.ai.puremvc.ApplicationConstants;
	import org.shopen.ai.puremvc.model.project.ProjectsProxy;
	import org.shopen.ai.puremvc.view.project.components.ItemSelector;

	public class ProjectSelectorMediator extends Mediator
	{
		public static const NAME : String = "ProjectSelectorMediator";
		
		public function ProjectSelectorMediator(viewComponent:Object=null)
		{
			super(ProjectSelectorMediator.NAME, viewComponent);
		}
		
		override public function getMediatorName():String
		{
			return ProjectSelectorMediator.NAME;
		}
		
		protected function get selector() : ItemSelector
		{
			return viewComponent as ItemSelector;
		}
		
		protected function get selectedIndex() : Number
		{
			var result : Number = selector.selectedIndex;
			return result;
		}
		protected function set selectedIndex(value : Number) : void
		{
			if (value >= 0)			
				selector.selectedIndex = value;
			else
				selector.selectedIndex = -1; //deselect
		}
		
		protected function get selectedId() : String
		{
			var result : String = "";
			if (selectedIndex >= 0)
			{
				result = (selector.dataProvider as ArrayCollection).getItemAt(selectedIndex).id.toString();
			}
			return result;
		}
		
		override public function listNotificationInterests():Array
		{
			return [ProjectsProxy.PROJECTS_META_INITIALIZED,
					ApplicationConstants.SELECT_PROJECT,
					ApplicationConstants.START_SEARCHING,
					ApplicationConstants.END_SEARCHING];
		}
		
		override public function handleNotification(notification:INotification):void
		{
			switch(notification.getName())
			{
				case ProjectsProxy.PROJECTS_META_INITIALIZED:
					initProjects(notification.getBody() as ArrayCollection);
					break;
				case ApplicationConstants.START_SEARCHING:
					selector.enabled = false;
					break;				
				case ApplicationConstants.END_SEARCHING:
					selector.enabled = true;
					break;
			}
		}
		
		private function initProjects(projectsArr : ArrayCollection) : void
		{
			selector.dataProvider = projectsArr;
			selector.labelField = "title";
			selector.toolTipField = "title";
			selector.addEventListener(ItemClickEvent.ITEM_CLICK, itemClickListener);
		}
		
		private function itemClickListener(event : ItemClickEvent) : void
		{
			if (selectedIndex != -1)
			{
				sendNotification(ApplicationConstants.SELECT_PROJECT, selectedId);
			}
		}
	}
}